
package com.onlyxiahui.common.utils.base.net.ssl;

import java.io.FileInputStream;
import java.io.InputStream;
import java.security.KeyStore;

import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;

/**
 * Description <br>
 * Date 2021-01-08 16:49:37<br>
 * 
 * @author XiaHui [onlovexiahui@qq.com]<br>
 * @since 1.0.0
 */

public class SslContextUtil {

	public static SSLContext createSSLContextByFilePath(String type, String filePath, String password) throws Exception {
		FileInputStream is = new FileInputStream(filePath);
		return createSSLContext(type, is, password);
	}

	public static SSLContext createSSLContextByClassPath(String type, String classPath, String password) throws Exception {
		InputStream is = SslContextUtil.class.getResourceAsStream(classPath);
		return createSSLContext(type, is, password);
	}

	public static SSLContext createSSLContext(String type, InputStream ksInputStream, String password) throws Exception {
		password = (null == password ? "" : password);
		KeyStore ks = KeyStore.getInstance(type); /// "JKS"
		// InputStream ksInputStream = new FileInputStream(path); /// 证书存放地址
		ks.load(ksInputStream, password.toCharArray());
		// KeyManagerFactory充当基于密钥内容源的密钥管理器的工厂。
		KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());// getDefaultAlgorithm:获取默认的 KeyManagerFactory 算法名称。
		kmf.init(ks, password.toCharArray());
		// SSLContext的实例表示安全套接字协议的实现，它充当用于安全套接字工厂或 SSLEngine 的工厂。
		SSLContext sslContext = SSLContext.getInstance("TLS");
		sslContext.init(kmf.getKeyManagers(), null, null);
		return sslContext;
	}
}
